import config from "../config"
import { lazyReportCache } from "../report"
import { getPaths } from "../utils/getPath"

/**
 * 手动上报
 * 
<button @click="click">手动上报</button>

methods: {
  click(event) {
    this.$monitor.tracker(event) // 手动上报
    // do something ...
  }
}
 */
export function tracker(event) {
  if (config.trackerAll) {
    return // 如果是全自动上报，则不需要手动上报
  }

  const data = getData(event)

  lazyReportCache('action', data)
}
/**
 * 自动上报
 * trackerAll = true 所有元素都上报
 * trackerAll = false 只上报有 data-tracker 属性的元素
 * <button data-tracker >点击</button>
 */
export function autoTracker() {
  ['click', 'keydown', 'blur', 'focus', 'touchstart', 'touchend'].forEach(eventType => {
    // 防抖
    const action = debounce(event => {
      const target = event.target;
      const dataTracker = target.getAttribute('data-tracker'); 

      if (dataTracker || config.trackerAll) {
        const data = getData(event)
        lazyReportCache('action', data)
      }
    })

    document.addEventListener(eventType, action)
  })
}

function getData(event) {
  const target = event.target

  return {
    eventType: event.type,
    tagName: target.tagName,
    x: event.x,
    y: event.y,
    path: getPaths(event),
    value: target.value || target.innerText,
  }
}

function debounce(callback, wait=300) {
  let timer = null

  return function(...args){
    if (timer) {
      clearTimeout(timer)
    }

    timer = setTimeout(() => {
      callback.call(this, ...args)
      timer = null
    }, wait)
    
  }
}
